package com.vmock.base.utils;

import cn.hutool.core.util.CharsetUtil;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;

/**
 * 文件处理工具类
 *
 * @author mock
 */
@UtilityClass
public class FileUtils {

    public static final String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    private static final String MSIE = "MSIE";

    private static final String FIREFOX = "Firefox";

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    @SneakyThrows
    public static void writeBytes(String filePath, OutputStream os) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }
        @Cleanup FileInputStream fis = new FileInputStream(file);
        byte[] b = new byte[1024];
        int length;
        while ((length = fis.read(b)) > 0) {
            os.write(b, 0, length);
        }
        os.close();
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists() && file.delete()) {
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains(MSIE)) {
            // IE浏览器
            filename = URLEncoder.encode(filename, CharsetUtil.UTF_8);
            filename = filename.replace("+", " ");
        } else if (agent.contains(FIREFOX)) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), CharsetUtil.ISO_8859_1);
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, CharsetUtil.UTF_8);
        }
        return filename;
    }
}
